package 并发编程16.Lock和Condition的使用;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * @author idea
 * @data 2019/2/17
 */
public class MyLock implements Lock {

    private final Sync sync=new Sync();

    private static final int GET = 1;

    private static final int CANCEL = 0;


    @Override
    public void lock() {
        //acquire里面会有代码去调用tryAcquire的内容
        sync.acquire(GET);
        System.out.println("加锁操作");
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {
        sync.acquireInterruptibly(GET);
    }

    @Override
    public boolean tryLock() {
        return sync.tryAcquire(GET);
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        //如果一致堵塞可以用这个函数来设置时长限制
        return sync.tryAcquireNanos(GET,unit.toNanos(time));
    }

    @Override
    public void unlock() {
        sync.release(GET);
    }

    @Override
    public Condition newCondition() {
        return sync.newCondition();
    }

    private static class Sync extends AbstractQueuedSynchronizer {


        @Override
        protected boolean tryAcquire(int arg) {
            if (compareAndSetState(CANCEL, GET)) {
                //设置当前线程获取锁
                setExclusiveOwnerThread(Thread.currentThread());
                return true;
            }
            return false;
        }

        @Override
        protected boolean tryRelease(int arg) {
            if (getState() == CANCEL) {
                throw new IllegalMonitorStateException();
            } else {
                setExclusiveOwnerThread(null);
                setState(GET);
                return true;
            }
        }

        //返回一个condition队列
        Condition newCondition() {
            return new ConditionObject();
        }


        /**
         * 判断当前独占式环境中是否获取到了锁
         *
         * @return
         */
        @Override
        protected boolean isHeldExclusively() {
            return getState() == GET;
        }
    }

    public static void main(String[] args) {
        MyLock myLock=new MyLock();
        myLock.lock();
        System.out.println("this");
        myLock.unlock();
    }
}
